<template>
  <div class="p-4">
    <el-card>
      <template #header>
        <div class="flex justify-between">
          <div>
            新增销售单
            <!-- （商品类型：{{
              SeriesList.find(s => s.SeriesId == dataList[currentIndex].SeriesId)?.SeriesName || '无'
            }}） -->
          </div>
          <div>
            本单合计：<span class="text-red-600">{{
              formatPrice(totalOrderMoney)
            }}</span>
            元
          </div>
        </div>
      </template>
      <el-form :model="form" :rules="rules" label-width="80px" inline>
        <el-form-item required label="客户名称" prop="customerName">
          <el-select
            v-model="form.customerName"
            placeholder="选择客户"
            style="width: 100px"
          >
            <el-option
              v-for="(item, index) in customerList"
              :key="index"
              :label="item.UserName"
              :value="item.UserName"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item required label="代理品牌" prop="PartnerBrand">
          <el-select
            v-model="form.PartnerBrand"
            placeholder="选择品牌"
            style="width: 100px"
          >
            <el-option
              v-for="(item, index) in brandList"
              :key="index"
              :label="item.BrandName"
              :value="item.BrandName"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item required label="交货时间">
          <el-date-picker
            v-model="form.deliveryTime"
            type="date"
            format="YYYY年MM月DD日"
            value-format="YYYY-MM-DD"
            placeholder="交货时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="注册号码">
          <el-input v-model="form.registerPhone" disabled></el-input>
        </el-form-item>
        <el-form-item label="客户习惯"> 无 </el-form-item>
      </el-form>
    </el-card>
    <el-row
      :gutter="20"
      class="mt-2 pl-[1px] min-h-60vh"
      style="margin-left: 0"
    >
      <el-col
        :lg="2"
        style="box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12); padding: 0"
      >
        <el-row
          class="text-[#3e9eff] text-[17px] bg-[#E8F2FD] py-3 hover:opacity-80 cursor-pointer"
          style="border-bottom: 3px solid #3e9eff"
          @click="addData"
        >
          <el-col :span="2" :offset="3">
            <el-icon class="text-[20px] mt-[1px]"><CirclePlus /></el-icon>
          </el-col>
          <el-col :span="14" :offset="3">
            <span class="text-[15px]">新增订单</span>
          </el-col>
        </el-row>
        <el-row
          v-for="(item, index) in dataList"
          class="flex items-center justify-center text-[17px] py-4 h-13"
          :key="index"
          @click="currentIndex = index"
        >
          <el-col :span="2" :offset="3">
            <transition name="fade">
              <div
                v-if="index == currentIndex"
                class="w-2 h-2 mr-6 bg-[#3e9eff] rounded-full"
              ></div>
            </transition>
          </el-col>
          <el-col :span="14" :offset="3">
            <span
              :class="{
                'font-bold text-[#3e9eff]': index == currentIndex,
                'cursor-pointer text-[15px]': true,
              }"
              >订单{{ index + 1 }}</span
            >
          </el-col>
        </el-row>
      </el-col>
      <el-col :lg="22">
        <el-card v-if="dataList.length != 0">
          <div class="flex justify-between">
            <div class="text-lg">订单{{ currentIndex + 1 }}</div>
            <div>
              <el-button
                type="primary"
                plain
                class="bg-white"
                @click="handleCopy"
                >复制并新增</el-button
              >
              <!-- <el-button type="primary" plain class="bg-white"
                ><span class="mr-1">更多操作</span
                ><el-icon><CaretBottom /></el-icon
              ></el-button> -->
            </div>
          </div>
          <div
            class="p-1 flex gap-8 items-center rounded p-2 px-4 mt-2"
            style="border: 1px solid #ddd"
          >
            <div class="flex items-center">
              <span class="text-red-500 mr-1 self-start mt-[5px]">*</span>
              <span class="whitespace-nowrap mr-2">产品</span>
              <el-select
                v-model="dataList[currentIndex].SeriesId"
                placeholder="产品系列"
                class="w-40"
              >
                <el-option
                  v-for="item in seriesList"
                  :key="item.SeriesId"
                  :label="item.SeriesName"
                  :value="item.SeriesId"
                >
                </el-option>
              </el-select>
            </div>
          </div>
          <div class="rounded p-2 px-4 mt-2" style="border: 1px solid #ddd">
            <el-descriptions
              title="基本信息"
              size="small"
              :column="4"
              border
              v-loading="loading"
            >
              <el-descriptions-item
                v-for="(item, index) in columnsBasic"
                :key="index"
              >
                <template #label>
                  <div
                    class="xl:text-[14px] lg:text-[16px] text-center whitespace-nowrap"
                  >
                    {{ item.AttrName }}
                  </div>
                </template>
                <template #default>
                  <template
                    v-if="
                      getSpecificSetting(
                        dataList[currentIndex].SeriesId,
                        item.AttrKeyName,
                        'IsVisible'
                      )
                    "
                  >
                    <el-input
                      :id="'field-basic-' + index"
                      class="none-border-input"
                      v-if="
                        getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'InputType'
                        ) == 1
                      "
                      v-model="dataList[currentIndex][item.AttrKeyName]"
                      :type="
                        inputModeMap[
                          getSpecificSetting(
                            dataList[currentIndex].SeriesId,
                            item.AttrKeyName,
                            'InputType2'
                          )
                        ].value
                      "
                      :disabled="
                        getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'InputType'
                        ) == 3
                      "
                      :placeholder="`请输入${item.AttrName}`"
                      :bordered="false"
                      @blur="
                        blurEvent(
                          dataList[currentIndex],
                          index,
                          item.AttrKeyName
                        )
                      "
                      @keydown="onKeydown($event, index, 'basic')"
                    ></el-input>
                    <el-select
                      :id="'field-basic-' + index"
                      v-else-if="
                        getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'InputType'
                        ) == 0
                      "
                      v-model="dataList[currentIndex][item.AttrKeyName]"
                      class="border-0 none-border-select"
                      @change="
                        blurEvent(
                          dataList[currentIndex],
                          index,
                          item.AttrKeyName
                        )
                      "
                    >
                      <el-option
                        v-for="p in getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'AttrValue'
                        )
                          .replaceAll('，', ',')
                          .split(',')"
                        :key="p"
                        :label="p"
                        :value="p"
                      >
                      </el-option>
                    </el-select>
                    <el-button
                      type="primary"
                      :icon="Upload"
                      link
                      v-else-if="
                        getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'InputType'
                        ) == 2
                      "
                      @click="openPictureModal"
                      >上传图片
                      <span
                        v-if="
                          dataList[currentIndex].AttatchUrl.split(',').filter(
                            Boolean
                          ).length !== 0
                        "
                        class="ml-1"
                        >({{
                          dataList[currentIndex].AttatchUrl.split(",").filter(
                            Boolean
                          ).length
                        }})</span
                      >
                    </el-button>
                  </template>
                  <template v-else>
                    <div class="w-20">/</div>
                  </template>
                </template>
              </el-descriptions-item>
            </el-descriptions>
            <el-descriptions
              title="结算信息"
              size="small"
              :column="4"
              border
              class="mt-3"
            >
              <el-descriptions-item
                v-for="(item, index) in columnsAccount"
                :key="index"
              >
                <template #label>
                  <div
                    class="xl:text-[14px] lg:text-[16px] text-center whitespace-nowrap"
                  >
                    {{ item.AttrName }}
                  </div>
                </template>
                <template #default>
                  <template
                    v-if="
                      getSpecificSetting(
                        dataList[currentIndex].SeriesId,
                        item.AttrKeyName,
                        'IsVisible'
                      )
                    "
                  >
                    <el-input
                      class="none-border-input"
                      :id="'field-account-' + index"
                      v-if="
                        getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'InputType'
                        ) == 1
                      "
                      v-model="dataList[currentIndex][item.AttrKeyName]"
                      :type="
                        inputModeMap[
                          getSpecificSetting(
                            dataList[currentIndex].SeriesId,
                            item.AttrKeyName,
                            'InputType2'
                          )
                        ].value
                      "
                      :disabled="
                        getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'InputType2'
                        ) == 3
                      "
                      :placeholder="`请输入${item.AttrName}`"
                      :bordered="false"
                      @blur="
                        blurEvent(
                          dataList[currentIndex],
                          index,
                          item.AttrKeyName
                        )
                      "
                      @keydown="onKeydown($event, index, 'account')"
                    ></el-input>
                    <el-select
                      :id="'field-account-' + index"
                      v-else-if="
                        getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'InputType'
                        ) == 0
                      "
                      v-model="dataList[currentIndex][item.AttrKeyName]"
                      class="border-0 none-border-select"
                    >
                      <el-option
                        v-for="p in getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'AttrValue'
                        )
                          .replaceAll('，', ',')
                          .split(',')"
                        :key="p"
                        :label="p"
                        :value="p"
                      >
                      </el-option>
                    </el-select>
                    <el-button
                      type="primary"
                      :icon="Upload"
                      link
                      v-else-if="
                        getSpecificSetting(
                          dataList[currentIndex].SeriesId,
                          item.AttrKeyName,
                          'InputType'
                        ) == 2
                      "
                      @click="openPictureModal"
                      >上传图片
                      <span
                        v-if="
                          dataList[currentIndex].AttatchUrl.split(',').filter(
                            Boolean
                          ).length !== 0
                        "
                        class="ml-1"
                        >({{
                          dataList[currentIndex].AttatchUrl.split(",").filter(
                            Boolean
                          ).length
                        }})</span
                      >
                    </el-button>
                  </template>
                  <template v-else>
                    <div>/</div>
                  </template>
                </template>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
        <el-card v-else class="min-h-full">
          <el-empty description="请添加订单"></el-empty>
        </el-card>
      </el-col>
    </el-row>
    <el-affix position="bottom">
      <div
        class="flex items-center justify-end gap-2 bg-white p-4 mt-2"
        style="box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12)"
      >
        <el-button
          class="w-25"
          size="large"
          type="default"
          @click="handleCancel"
          >取消</el-button
        >
        <el-button
          class="w-25"
          size="large"
          type="primary"
          @click="handleSubmit"
          >保存</el-button
        >
      </div>
    </el-affix>
    <el-dialog title="附图" width="700" v-model="pictureOpen">
      <ImageUpload v-model="pictureList" />
      <template #footer>
        <el-button @click="pictureOpen = false">取 消</el-button>
        <el-button type="primary" @click="pictureConfirm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ElMessage } from "element-plus";
import { Upload } from "@element-plus/icons-vue";
import { useRouter } from "vue-router";
import useOrderDataStore from "@/store/modules/orderData";
import useOrderAttrStore from "@/store/modules/orderAttrs";
import { onBeforeMount, onMounted } from "vue";
import { createUniqueString, deepClone } from "../../../../utils";
import { settlementCols } from "@/utils/map.js";
import { seriesQueryApi } from "@/api/order/series/index.js";
import {
  attrQueryApi,
  computeQueryApi,
  offerQueryApi,
} from "@/api/order/attr/index.js";
import { brandQueryApi } from "@/api/order/brand/index.js";
import { customerQueryApi } from "@/api/order/customer/index.js";
import {
  orderQueryApi,
  saleOrderQueryApi,
  saleOrderDetailApi,
  saleOrderAddApi,
} from "@/api/order/manage/index.js";
import { orderAttrsMap2, getAttrKey, inputModeMap } from "@/utils/map";
import { formatPrice, evaluate, timeStampFormatter } from "@/utils";
import dayjs from "dayjs";

const orderDataStore = useOrderDataStore();
const router = useRouter();
const route = useRoute();

const attrsStore = useOrderAttrStore();
const productList = attrsStore.orderAttrs;
const columns = ref(orderDataStore.columns);
const columnsBasic = ref([]);
const columnsAccount = ref([]);
const form = ref(orderDataStore.saleInfo);
const dataList = ref(orderDataStore.orderData);
const saleDataList = ref(orderDataStore.saleOrderData);
const brandList = ref([]);
const currentIndex = ref(0);
const customerList = ref([]);
const rules = ref({
  customerName: [
    { required: true, message: "请输入客户名称", trigger: "change" },
  ],
});
const totalOrderMoney = computed(() => {
  // 订单金额计算
  let sum = 0;
  dataList.value.forEach((item) => {
    sum += item.Money_Total;
  });
  return sum;
});
const pictureList = ref([]);
const seriesList = ref(orderDataStore.seriesData);
const attrsList = ref(orderDataStore.attrsData);
const computeList = ref(orderDataStore.computeData);
const offerList = ref(orderDataStore.offerData);
const currentSaleRow = ref(orderDataStore.currentSaleRow);
const pictureOpen = ref(false);
const loading = ref(false);
async function getData() {
  loading.value = true;

  columnsBasic.value = columns.value.filter(
    (item) =>
      !item.AttrKeyName.toLowerCase().includes("money") &&
      !item.AttrKeyName.toLowerCase().includes("price")
  );
  columnsAccount.value = columns.value.filter(
    (item) =>
      item.AttrKeyName.toLowerCase().includes("money") ||
      item.AttrKeyName.toLowerCase().includes("price")
  );
  const res1 = await brandQueryApi();
  brandList.value = res1.Data;
  const res4 = await customerQueryApi();
  customerList.value = res4.Data || [];

  loading.value = false;
}

onMounted(() => {
  getData();
});
function invisibleColFilter() {
  // let maxKey = 0;
  // let max = 0;
  // for (let key in attrsList) {
  //   if (attrsList[key].length > max) {
  //     max = attrsList[key].length;
  //     maxKey = key;
  //   }
  // }
  // columns.value = attrsList[maxKey];
  // 如果所有产品系列都设置不显示则过滤该列
  columns.value = columns.value.filter((col) => {
    return Object.values(attrsList.value).some((attrs) => {
      return attrs.find((a) => a.AttrName == col.AttrName)?.IsVisible;
    });
  });
}

function addData() {
  let obj = {};
  if (seriesList.value.length !== 0) {
    obj.SeriesId = seriesList.value[0].SeriesId;
    obj.SeriesName = seriesList.value[0].SeriesName;
  } else {
    obj.SeriesId = 0;
  }
  obj.unsaved = true; // 用于在循环请求添加订单的时候判断是否是用户刚刚新增的数据
  obj.id = createUniqueString();
  obj = setDefaultValue(obj);
  dataList.value.push(obj);
  orderDataStore.setOrderData(dataList.value);
}
function getSpecificSetting(seriesId, AttrKeyName, settingName) {
  let p = attrsList.value["attrs" + seriesId].find(
    (item) => item.AttrKeyName == AttrKeyName
  );
  return p && p[settingName];
}
function handleCopy() {
  let obj = deepClone(dataList.value[currentIndex.value]);
  dataList.value.push(obj);
  orderDataStore.setOrderData(dataList.value);
  ElMessage.success("复制成功");
}
function handleCancel() {
  orderDataStore.setOrderData(dataList.value);
  router.push("./orders");
}
async function handleSubmit() {
  // 调用保存接口
  if (!form.value.customerName) {
    ElMessage.warning("请选择客户");
    return;
  }
  if (!form.value.PartnerBrand) {
    ElMessage.warning("请选择代理品牌");
    return;
  }
  if (!form.value.deliveryTime) {
    ElMessage.warning("请选择交货时间");
    return;
  }
  if (
    typeof form.value.deliveryTime == "string" &&
    form.value.deliveryTime.includes("Date(")
  ) {
    form.value.deliveryTime = timeStampFormatter(form.value.deliveryTime);
    if (form.value.deliveryTime == "无") {
      ElMessage.warning("交货时间格式不正确");
      return;
    }
  }

  let AttrLists = [];
  dataList.value.map((item) => {
    let AttrList = [];
    for (let key in item) {
      if (item.unsaved && item[key] && !["id", "unsaved"].includes(key)) {
        AttrList.push({ Name: key, Value: item[key] });
        if (AttrList.at(-1).Name == "SeriesName") {
          AttrList.at(-1).Name = "Field1";
        }
      }
    }
    AttrLists.push(AttrList);
  });
  // 判断是否是已存在销售单的子单，然后给对应格式的OrderCode
  // 子单：YYMMDD-nnn-nn，总单：YYMMDD-nnn-nn
  let flag = dataList.value.some((item) => !item.unsaved);
  let no;
  if (flag) {
    no = dataList.value
      .map((item) => item.OrderCode)
      .filter(Boolean)
      .sort()
      .at(-1)
      .split("-")[2];
    no =
      currentSaleRow.value.OrderCode +
      "-" +
      String(+no + 1).padStart("2", "0");
  } else {
    no = saleDataList.value
      .map((item) => item.TOrderCode)
      .sort()
      .at(-1)
      .split("-")[1];
    no = dayjs().format("YYMMDD") + "-" + String(+no + 1).padStart("3", "0");
  }
  for (let i = 0; i < dataList.value.length; i++) {
    if (AttrLists[i].length !== 0)
      await saleOrderAddApi({
        OrderCode: no,
        CustomerName: form.value.CustomerName,
        BrandName: form.value.PartnerBrand,
        CreateTime: dayjs().format("YYYY-MM-DD"),
        OrderTime: form.value.deliveryTime,
        SeriesName: dataList.value[0].Field1 || dataList.value[0].SeriesName,
        AttrList: AttrLists[i]
      });
  }
  ElMessage.success("保存成功");
  dataList.value = [];
  router.push("./orders");
}
function openPictureModal() {
  dataList.value[currentIndex.value].pictureSelect = true;
  pictureList.value = dataList.value[currentIndex.value].Picture;
  pictureOpen.value = true;
}
function pictureConfirm() {
  pictureOpen.value = false;
  dataList.value.forEach((item) => {
    if (item.pictureSelect) {
      item.Picture = pictureList.value;
      delete item.pictureSelect;
    }
  });
}
function onKeydown(e, i, group = "basic") {
  // 行号
  let rowNo = Math.floor(i / 4);
  if (e.keyCode == 38) {
    //按上键
    //首行判断
    if (rowNo == 0) {
      return;
    }
    document.querySelector(`#field-${group}-${i - 4}`)?.focus();
  } else if (e.keyCode == 40) {
    //按下键
    //末行同列判断
    if (
      i + 4 >
      (group == "basic" ? columnsBasic.length : columnsAccount.length) - 1
    ) {
      return;
    }
    document.querySelector(`#field-${group}-${i + 4}`)?.focus();
  }
}
function blurEvent(row, curIndex, columnKey) {
  // allowDisappear.value = true;
  if (row[columnKey] !== row[columnKey + "_old"]) {
    // 发送请求 将数据保存到服务器
    // ElMessage({
    //   message: "修改成功",
    //   type: "success",
    //   duration: 1000,
    // });
    columnCompute(row, columnKey);
  }
}
function columnCompute(row, columnKey) {
  // 属于计算字段或存在于计算属性的公式中进入计算
  let computeTargetList = computeList.value["attrs" + row.SeriesId].filter(
    (c) =>
      c.AttrName == orderAttrsMap2[columnKey] ||
      c.AttrValue.includes(orderAttrsMap2[columnKey])
  );
  computeTargetList.forEach((target) => {
    computeAttrCalc(row, target);
  });
  // popoverInfo.computes.forEach((item) => {
  //   item.targetValue = row[getAttrKey(item.target)];
  // });

  // 存在于报价方式的公式中进入计算
  let offerTargetList = offerList.value["attrs" + row.SeriesId].filter(
    (c) =>
      c.AttrName == orderAttrsMap2[columnKey] ||
      c.AttrValue.includes(orderAttrsMap2[columnKey])
  );
  offerTargetList.forEach((target) => {
    target.AttrName = "结算金额";
    computeAttrCalc(row, target);
  });
  // popoverInfo.offers.forEach((item) => {
  //   item.targetValue = row[getAttrKey(item.target)];
  // });
}
function computeAttrCalc(row, computeTarget) {
  let { SeriesId } = row;
  let formula = computeTarget.AttrValue.replace(/×/g, "*")
    .replace(/÷/g, "/")
    .replace(/（/g, "(")
    .replace(/）/g, ")")
    .replace(/【/g, "[")
    .replace(/】/g, "]");
  for (let key in row) {
    let attr = attrsList.value["attrs" + SeriesId].find(
      (attr) => attr.AttrKeyName == key
    );
    if (attr) formula = formula.replaceAll(attr.AttrName, row[key] || 0);
  }
  row[getAttrKey(computeTarget.AttrName)] = evaluate(formula).toFixed(2);
}
function setDefaultValue(row) {
  columns.value.forEach((col) => {
    if (!row.SeriesId) {
      let res = seriesList.value.find((item) => item.SeriesName == row.Field1);
      if (res) row.SeriesId = res.SeriesId;
    }
    // 无输入，且有设置默认值
    if (!row[col.AttrKeyName] && col.DefaultValue) {
      row[col.AttrKeyName] = col.DefaultValue;
    } else if (!row[col.AttrKeyName]) {
      row[col.AttrKeyName] = "";
    }
  });
  return row;
}
</script>
<style scoped lang="scss">
.none-border-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 0px var(--el-input-border-color, var(--el-border-color))
    inset;
}
.none-border-select ::v-deep .el-select__wrapper {
  box-shadow: none;
}
.none-border-select ::v-deep .is-hovering {
  box-shadow: none !important;
}
.fade-enter-active,
.fade-leave-active {
  transition: all 0.2s;
}
.fade-enter-from {
  opacity: 0;
}
.fade-leave-to {
  opacity: 0;
}
</style>
